package com.neusoft.weekreport.component.simpleUploader.controller;

import com.neusoft.weekreport.component.simpleUploader.entity.FileChunkDTO;
import com.neusoft.weekreport.component.simpleUploader.entity.FileChunkResultDTO;
import com.neusoft.weekreport.component.simpleUploader.entity.RestApiResponse;
import com.neusoft.weekreport.component.simpleUploader.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author liu.jiaming
 * @Create 2022/11/1 9:32
 */
@RestController
@RequestMapping("upload")
public class UploaderController {

    @Autowired
    private UploadService uploadService;

    /**
     * 检查分片是否存在
     *
     * @return
     */
    @GetMapping("chunk")
    public RestApiResponse<Object> checkChunkExist(FileChunkDTO chunkDTO,HttpServletResponse response) {
        FileChunkResultDTO fileChunkCheckDTO;
        try {
            fileChunkCheckDTO = uploadService.checkChunkExist(chunkDTO,response);
            //1.第一个分片返回状态码204,其余分片状态码,解决第一个分片接收不到
            //2.判断秒传不上传第一个分片及其他分片
            if (chunkDTO.getChunkNumber().equals(1) && fileChunkCheckDTO.getSkipUpload() != true){
                response.setStatus(204);
            }
            return RestApiResponse.success(fileChunkCheckDTO);
        } catch (Exception e) {
            return RestApiResponse.error(e.getMessage());
        }
    }


    /**
     * 上传文件分片
     *
     * @param chunkDTO
     * @return
     */
    @PostMapping("chunk")
    public RestApiResponse<Object> uploadChunk(FileChunkDTO chunkDTO) {
        try {
            System.out.println("post方式开始上传分片---------------");
            System.out.println("chunkDTO.getIdentifier:"+chunkDTO.getIdentifier()+"chunkDTO.getPath"+chunkDTO.getPath()+"--------");
            uploadService.uploadChunk(chunkDTO);
            return RestApiResponse.success(chunkDTO.getIdentifier());
        } catch (Exception e) {
            return RestApiResponse.error(e.getMessage());
        }
    }

    /**
     * 请求合并文件分片
     *
     * @param chunkDTO
     * @return
     */
    @PostMapping("merge")
    public RestApiResponse<Object> mergeChunks(@RequestBody FileChunkDTO chunkDTO) {
        try {
            boolean success = uploadService.mergeChunk(chunkDTO.getIdentifier(), chunkDTO.getFilename(), chunkDTO.getTotalChunks(),chunkDTO.getPath());
//            return RestApiResponse.flag(success);
            return RestApiResponse.success(chunkDTO.getFilename());
        } catch (Exception e) {
            return RestApiResponse.error(e.getMessage());
        }
    }
}